package com.yufu.baidu.ocr;

import android.util.Log;

import java.io.File;

import android.content.Context;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;

public class BaiduOcr {

  Context context;

  private boolean hasGotToken = false;

  private final static String TAG = "BaiduOcr";

  public BaiduOcr(Context context) {
    this.context = context;
    initAccessToken();
  }

  public static void log(String value) {
    Log.i(TAG, value);
  }

  public String echo(String value) {
    Log.i(TAG, value);
    return value;
  }

  private boolean checkTokenStatus() {
    if (!hasGotToken) {
      Toast.makeText(context.getApplicationContext(), "token还未成功获取", Toast.LENGTH_LONG).show();
    }
    return hasGotToken;
  }

  /**
   * 以license文件方式初始化
   */
  private void initAccessToken() {
    OCR.getInstance(context.getApplicationContext()).initAccessToken(new OnResultListener<AccessToken>() {
      @Override
      public void onResult(AccessToken accessToken) {
        String token = accessToken.getAccessToken();
        hasGotToken = true;
      }

      @Override
      public void onError(OCRError error) {
        error.printStackTrace();
        echo("licence方式获取token失败:" + error.getMessage());
      }
    }, context.getApplicationContext());
  }

  /**
   * 自定义license的文件路径和文件名称，以license文件方式初始化
   */
  private void initAccessTokenLicenseFile(String licensePath) {
    OCR.getInstance(context.getApplicationContext()).initAccessToken(new OnResultListener<AccessToken>() {
      @Override
      public void onResult(AccessToken accessToken) {
        String token = accessToken.getAccessToken();
        hasGotToken = true;
      }

      @Override
      public void onError(OCRError error) {
        error.printStackTrace();
        echo("自定义文件路径licence方式获取token失败:" + error.getMessage());
      }
    }, licensePath, context.getApplicationContext());
  }
}
